package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.UniversityDataCollectionMapper;
import com.cmii.sjw.department.control.jsc.model.UniversityDataCollection;
import com.cmii.sjw.department.control.jsc.model.dto.UniversityDataCollectionDTO;
import com.cmii.sjw.department.control.jsc.service.UniversityDataCollectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;


@Slf4j
@Service("UniversityDataCollectionService")
public class UniversityDataCollectionServiceImpl extends ServiceImpl<UniversityDataCollectionMapper, UniversityDataCollection> implements UniversityDataCollectionService {


    /**
     * 高校数据归集与共享统计表
     *
     * @return 列表
     */
    @Override
    public List<UniversityDataCollection> list() {
        LambdaQueryWrapper<UniversityDataCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(UniversityDataCollection::getTotalScore);
        return list(wrapper);
    }

    /**
     * 数据归集与共享统计
     *
     * @return 统计数据
     */
    @Override
    public UniversityDataCollectionDTO getCollectionStats() {
        List<UniversityDataCollection> list = this.list();

        int totalCatalog = 0;
        int totalCollection = 0;
        BigDecimal totalScore = BigDecimal.ZERO;

        for (UniversityDataCollection item : list) {
            totalCatalog += Optional.ofNullable(item.getCatalogCategories()).orElse(0);
            totalCollection += Optional.ofNullable(item.getCollectionCategories()).orElse(0);
            totalScore = totalScore.add(Optional.ofNullable(item.getTotalScore()).orElse(BigDecimal.ZERO));
        }

        UniversityDataCollectionDTO stats = new UniversityDataCollectionDTO();
        stats.setTotalCatalogCategories(totalCatalog);
        stats.setTotalCollectionCategories(totalCollection);
        if (!list.isEmpty()) {
            BigDecimal average = totalScore.divide(BigDecimal.valueOf(list.size()), 2, RoundingMode.HALF_UP);
            stats.setAverageTotalScore(average);
        } else {
            stats.setAverageTotalScore(BigDecimal.ZERO);
        }

        return stats;
    }
}
